package net.openvision.music.notenames;

import net.openvision.music.model.Clef;
import net.openvision.music.model.Length;
import net.openvision.music.model.Note;

public class DefaultNoteConverter implements NoteConverter {

	private static int[] charMapping;

	static {
		charMapping = new int[] { 5, 6, 0, 1, 2, 3, 4 };
	}

	@Override
	public Note convert(String value) {
		try {
			byte c = (byte) value.charAt(0);
			boolean sharp = (value.charAt(value.length() - 1) == '#');
			int octave = Integer.parseInt(value.substring(1, (sharp) ? value
					.length() - 1 : value.length()));
			int result = charMapping[(c - 65)] + ((sharp) ? 1 : 0) + 12
					* (octave + 1);
			if (result < 0 || result > 127)
				throw new IllegalArgumentException("Note pitch out of range.");
			return new Note(charMapping[(c - 65)], (sharp) ? 1 : 0,
					Length.QUARTER, Clef.NONE);
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("Illegal string format.", e);
		}
	}
}
